/**
 ********************************************************************
 * @author roocket
 * @file    file_lock.h
 * @version V0.0.0
 * @date    2024/4/25
 * @brief   This file is to indicate file lock functions. 
 * @attention Code file rules:
 * rule: file encoding use UTF8;
 * rule: max line length 120 characters;
 * rule: line separator \r\n;
 * rule: use clion auto code format tool.
 */
#include "file_lock.h"

int file_lock_init_key_of_door(const char *file)
{
	int fd;

	fd = open(file, O_RDWR | O_CREAT, 0666);
	if (-1 == fd) {
		perror("open file error");
		return -1;
	}
	return fd;
}

int file_lock_trywait_acquire(int fd, long lock_type, int (*file_callback)(void *what_to_do), void *what)
{
	struct flock lock;
	int res;

	/* append lock */
	lock.l_type = lock_type;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;

	/* wait for lock comes */
	res = fcntl(fd, F_SETLKW, &lock);
	if (-1 == res) {
		perror("fcntl error");
		return -1;
	}

	return file_callback(what); 
}

int file_lock_unlock_door(int fd)
{
	struct flock lock;
	int res;

	/* append lock */
	lock.l_type = F_UNLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;

	res = fcntl(fd, F_SETLK, &lock);
	if (-1 == res) {
		perror("fcntl error");
		goto out;
	}

    printf("lock released.\n");
    close(fd);
    return 0;
out:
	if (fd)
		close(fd);
	return -1;
}
